<?php
namespace app\api\controller;

class Trade extends Permission
{
    /**
     * 2024年06月19日
     * status 状态
     * 创建的时候为 0 等待录入各种信息
     * 提交后，变为待出单 10 等待保险部出单
     * 待付款 20
     * 付款完成后待上传保单 30 
     * 上传完整的保单后 已完成 200
     * 无法出单（等于废了）待定
     * */
    public function getList()
    {
        $page = isset($this->input_data['page']) ? $this->input_data['page'] : 1;
        $limit = isset($this->input_data['limit']) ? $this->input_data['limit'] : 15;
        $map = [];

        if( isset($this->input_data['area']) && $this->input_data['area'] != '') $map['b.area'] = ['LIKE','%'.$this->input_data['area'].'%'];
        if( isset($this->input_data['company']) && $this->input_data['company'] != '') $map['b.company'] = ['LIKE','%'.$this->input_data['company'].'%'];
        if( isset($this->input_data['plate_number']) && $this->input_data['plate_number'] != '') $map['b.plate_number'] = ['LIKE','%'.$this->input_data['plate_number'].'%'];
        if( isset($this->input_data['create_user']) && $this->input_data['create_user'] != '') $map['a.create_user'] = ['LIKE','%'.$this->input_data['create_user'].'%'];
        if( isset($this->input_data['judge_user']) && $this->input_data['judge_user'] != '') $map['a.judge_user'] = ['LIKE','%'.$this->input_data['judge_user'].'%'];
        if( isset($this->input_data['to_judge_user']) && $this->input_data['to_judge_user'] != '') $map['a.to_judge_user'] = ['LIKE','%'.$this->input_data['to_judge_user'].'%'];
        if( isset($this->input_data['status']) && $this->input_data['status'] != 99999999 ) $map['a.status'] = $this->input_data['status'];
        if( isset($this->input_data['dianfu']) && $this->input_data['dianfu'] != 99999999 )
        {
            if($this->input_data['dianfu'] == 0)  $map['a.dianfu_amount'] = 0;
            if($this->input_data['dianfu'] == 1)  $map['a.dianfu_amount'] = ['>',0];
        }

        if( isset($this->input_data['fenqi']) && $this->input_data['fenqi'] != 99999999 ) 
        {
            if($this->input_data['fenqi'] == 0)  $map['a.fenqi_amount'] = 0;
            if($this->input_data['fenqi'] == 1)  $map['a.fenqi_amount'] = ['>',0];
        }

        //日期
        $sDate = isset($this->input_data['startDate']) ? strtotime($this->input_data['startDate']) : '';
        $eDate = isset($this->input_data['endDate']) ? strtotime($this->input_data['endDate']) : '';
        if($sDate)
        {
            $map['judge_time'] = ['>',$sDate];
        }
        if($sDate && $eDate)
        {
            $map['judge_time'] = ['between',[$sDate,$eDate+86400]];
        }
        if($sDate == 0 && $eDate > 0)
        {
            $map['judge_time'] = ['between',[0,$eDate+86400]];
        }

        if($this->post('area_id') > 0)
        {
            $map['area_id'] = $this->post('area_id');
        }
        else
        {
            $map['area_id'] = ['IN',$this->myAllAreaIds];
        }


        $total = db('Trade')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->where($map)->count();
        $rows = db('Trade')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number')->order('a.id', 'desc')->page($page,$limit)->where($map)->select();

        $cMap = $map;

        $cMap['a.status'] = 3;
        $backBxCount = db('Trade')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number')->where($cMap)->count();
        $cMap['a.status'] = 4;
        $backNqCount = db('Trade')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number')->where($cMap)->count();
        $cMap['a.status'] = 5;
        $judgeCount = db('Trade')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number')->where($cMap)->count();
        $cMap['a.status'] = 10;
        $sendCount = db('Trade')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number')->where($cMap)->count();
        $cMap['a.status'] = 20;
        $payCount = db('Trade')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number')->where($cMap)->count();
        $cMap['a.status'] = 30;
        $uploadCount = db('Trade')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number')->where($cMap)->count();
        $cMap['a.status'] = 190;
        $checkCount = db('Trade')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number')->where($cMap)->count();


        $list = [];
        foreach ($rows as $v) {
            $v = $this->_formatTradeData($v);
            $v = $this->_formatQt($v);
            $list[] = $v;
        }

        $badgeData = [
            'backBx' => $backBxCount,
            'backNq' => $backNqCount,
            'judge' => $judgeCount,
            'upload' => $uploadCount,
            'pay' => $payCount,
            'send' => $sendCount,
            'check' => $checkCount
        ];
        
        $data = [
            'total' => $total,
            'list' => $list,
            'badgeData' => $badgeData,
            'map' => $map
        ];
        $this->resSuc($data);
    }

    private function _formatTradeData($data)
    {
        $data['price'] = formatMoneyShow($data['price']);
        $data['paid'] = formatMoneyShow($data['paid']);
        $data['tax_price'] = formatMoneyShow($data['tax_price']);
        $data['qx_price'] = formatMoneyShow($data['qx_price']);
        $data['qx_paid'] = formatMoneyShow($data['qx_paid']);
        $data['syx_price'] = formatMoneyShow($data['syx_price']);
        $data['syx_paid'] = formatMoneyShow($data['syx_paid']);
        $data['qtx_price'] = formatMoneyShow($data['qtx_price']);
        $data['cpx_price'] = formatMoneyShow($data['cpx_price']);
        $data['cpx_paid'] = formatMoneyShow($data['cpx_paid']);
        $data['cyx_price'] = formatMoneyShow($data['cyx_price']);
        $data['cyx_paid'] = formatMoneyShow($data['cyx_paid']);
        $data['azx_price'] = formatMoneyShow($data['azx_price']);
        $data['azx_paid'] = formatMoneyShow($data['azx_paid']);
        $data['hyx_price'] = formatMoneyShow($data['hyx_price']);
        $data['hyx_paid'] = formatMoneyShow($data['hyx_paid']);
        $data['jyx_price'] = formatMoneyShow($data['jyx_price']);
        $data['jyx_paid'] = formatMoneyShow($data['jyx_paid']);
        $data['glf_price'] = formatMoneyShow($data['glf_price']);
        $data['glf_paid'] = formatMoneyShow($data['glf_paid']);
        $data['gps_price'] = formatMoneyShow($data['gps_price']);
        $data['gps_paid'] = formatMoneyShow($data['gps_paid']);
        $data['eb_price'] = formatMoneyShow($data['eb_price']);
        $data['eb_paid'] = formatMoneyShow($data['eb_paid']);
        $data['xx_price'] = formatMoneyShow($data['xx_price']);
        $data['xx_paid'] = formatMoneyShow($data['xx_paid']);
        $data['gz_price'] = formatMoneyShow($data['gz_price']);
        $data['gz_paid'] = formatMoneyShow($data['gz_paid']);
        $data['fw_price'] = formatMoneyShow($data['fw_price']);
        $data['fw_paid'] = formatMoneyShow($data['fw_paid']);
        $data['qt_paid'] = formatMoneyShow($data['qt_paid']);
        $data['diff_price'] = formatMoneyShow($data['diff_price']);
        $data['profit'] = formatMoneyShow($data['profit']);
        $data['custom_profit_target'] = formatMoneyShow($data['custom_profit_target']);
        $data['profit_target'] = formatMoneyShow($data['profit_target']);


        $data['dianfu_amount'] = formatMoneyShow($data['dianfu_amount']);
        $data['fenqi_charge_amount'] = formatMoneyShow($data['fenqi_charge_amount']);
        $data['fenqi_benjin'] = formatMoneyShow($data['fenqi_amount'] - $data['fenqi_first_pay']);
        $data['fenqi_amount'] = formatMoneyShow($data['fenqi_amount']);
        $data['fenqi_first_pay'] = formatMoneyShow($data['fenqi_first_pay']);
        $data['fenqi_first_pay_percent'] = $data['fenqi_first_pay_percent'] * 1;

        $data['payImages'] = json_decode($data['pay_images'],true);
        $data['doneTime'] = date('Y-m-d',$data['judge_time']);

        $data['toJudgeDate'] = date('Y-m-d',$data['to_judge_time']);
        $data['toJudgeTime'] = date('H:i',$data['to_judge_time']);
        $data['backDate'] = date('Y-m-d',$data['back_time']);
        $data['backTime'] = date('H:i',$data['back_time']);
        $data['judgeDate'] = date('Y-m-d',$data['judge_time']);
        $data['judgeTime'] = date('H:i',$data['judge_time']);
        $data['pay_time'] = $data['pay_time'] == 0 ? '' : date('Y-m-d H:i:s',$data['pay_time']);

        return $data;
    }

    public function getWatingBuyList()
    {
        $page = $this->post('page') ? $this->post('page') : 1;
        $limit = $this->post('limit') ? $this->post('limit') : 15;
        $map = [
            'a.status' => 10
        ];
        if($this->post('plate_number') != '') $map = $this->setMaps($map,'plate_number','LIKE');
        if($this->post('company') != '') $map = $this->setMaps($map,'company','LIKE');

        $total = db('Trade')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->where($map)->count();
        $rows = db('Trade')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number')->order('a.id', 'desc')->page($page,$limit)->where($map)->select();
        $list = [];
        foreach ($rows as $v) {
            $v['judge_time'] = date('Y-m-d H:i',$v['judge_time']);
            $list[] = $v;
        }


        $data = [
            'map' => $map,
            'list' => $list,
            'total' => $total
        ];
        $this->resSuc($data);
    }

    private function _formatQt($v)
    {
        $qt = explode(',', $v['qt_price']);
        $qtt = explode(',', $v['qt_title']);
        $qtPrice = 0;
        $qtList = [];
        foreach ($qt as $i => $q) {
            $qtPrice = bcadd($q,$qtPrice);  // 其他
            $qtList[] = [
                'title' => $qtt[$i],
                'price' => formatMoneyShow($q)
            ];
        }
        $v['qtList'] = $qtList;
        $v['qt_price'] = formatMoneyShow($qtPrice);

        return $v;
    }

    // 新的出单
    public function update()
    {
        # 添加出单记录
        $data = [
            'vehicle_id' => $this->input_data['vehicle_id'],
            'profit_target' => formatMoneySave($this->input_data['profit_target']),
            'custom_profit_flag' => $this->post('custom_profit_flag'),
            'custom_profit_target' => formatMoneySave($this->input_data['custom_profit_target']),
            'custom_profit_target_images' => $this->input_data['custom_profit_target_images'],
            'glf_price' => formatMoneySave($this->input_data['glf_price']),
            'glf_note' => $this->input_data['glf_note'],
            'gps_price' => formatMoneySave($this->input_data['gps_price']),
            'gps_note' => $this->input_data['gps_note'],
            'eb_price' => formatMoneySave($this->input_data['eb_price']),
            'eb_note' => $this->input_data['eb_note'],
            'xx_price' => formatMoneySave($this->input_data['xx_price']),
            'gz_price' => formatMoneySave($this->input_data['gz_price']),
            'fw_price' => formatMoneySave($this->input_data['fw_price']),
            // 'qt_price' => formatMoneySave($this->input_data['qt_price']),
            'remark' => $this->input_data['remark'],
            'create_user' => $this->user['realname'],
            'create_user_id' => $this->user['id'],
            'create_time' => time(),
        ];
        $qt = json_decode($this->input_data['qtList'],true);
        $qtTitle = [];
        $qtPrice = [];
        foreach ($qt as $v) {
            $qtTitle[] = $v['title'];
            $qtPrice[] = formatMoneySave($v['price']);
        }
        $data['qt_title'] = implode(',',$qtTitle);
        $data['qt_price'] = implode(',',$qtPrice);

        $tradeId = db('Trade')->insertGetId($data);

        # 更新应付总价
        $data = [
            'tradeId' => $tradeId
        ];
        action('common/Trade/updatePrice',$data);

        $this->_updateProfit($tradeId);

        # 创建保险报价申请
        if($this->input_data['insurance_remark'] != '') $this->_createOffer($tradeId);

        $this->resSuc('ok');
    }

    // 创建保险报价申请
    private function _createOffer($tradeId)
    {
        $data = [
            'trade_id' => $tradeId,
            'cate' => '人工申请',
            // 'remark_c' => $this->input_data['insurance_c_remark'],
            // 'remark_b' => $this->input_data['insurance_b_remark'],
            'remark' => $this->input_data['insurance_remark'],
            'vehicle_id' => $this->input_data['vehicle_id'],
            'company' => $this->input_data['company'],
            'plate_number' => $this->input_data['plate_number'],
        ];

        $other = json_decode($this->input_data['other'],true);
        foreach ($other as $v) {
            switch ($v) {
                case '超赔险':
                    $data['cp'] = 1;
                    break;
                case '货运险':
                    $data['hy'] = 1;
                    break;
                case '安责险':
                    $data['az'] = 1;
                    break;
                case '承运险':
                    $data['cy'] = 1;
                    break;
                case '驾意险':
                    $data['jy'] = 1;
                    break;
                
                default:
                    // code...
                    break;
            }
        }
        db('InsurancePlan')->insert($data);
    }
    

    // 旧的出单
    // public function updateOld()
    // {
    //     # 添加出单记录
    //     $data = [
    //         'vehicle_id' => $this->input_data['vehicle_id'],
    //         'glf_price' => formatMoneySave($this->input_data['glf_price']),
    //         'glf_paid' => formatMoneySave($this->input_data['glf_paid']),
    //         'gps_price' => formatMoneySave($this->input_data['gps_price']),
    //         'gps_paid' => formatMoneySave($this->input_data['gps_paid']),
    //         'eb_price' => formatMoneySave($this->input_data['eb_price']),
    //         'eb_paid' => formatMoneySave($this->input_data['eb_paid']),
    //         'xx_price' => formatMoneySave($this->input_data['xx_price']),
    //         'xx_paid' => formatMoneySave($this->input_data['xx_paid']),
    //         'gz_price' => formatMoneySave($this->input_data['gz_price']),
    //         'gz_paid' => formatMoneySave($this->input_data['gz_paid']),
    //         'fw_price' => formatMoneySave($this->input_data['fw_price']),
    //         'fw_paid' => formatMoneySave($this->input_data['fw_paid']),
    //         'qt_price' => formatMoneySave($this->input_data['qt_price']),
    //         'qt_paid' => formatMoneySave($this->input_data['qt_paid']),
    //         'price' => formatMoneySave($this->input_data['price']),
    //         'paid' => formatMoneySave($this->input_data['paid']),
    //         'pay_images' => $this->input_data['pay_images'],

    //         // 垫付的
    //         'dianfu_deadline' => $this->input_data['dianfu_deadline'],
    //         'dianfu_interest_rate' => $this->input_data['dianfu_interest_rate'],
    //         'dianfu_images' => $this->input_data['dianfu_images'],
    //         'dianfu_amount' => formatMoneySave($this->input_data['dianfu_amount']),
    //         'dianfu_times' => $this->input_data['dianfu_times'],

    //         // 分期的
    //         'fenqi_deadline' => $this->input_data['fenqi_deadline'],
    //         'fenqi_interest_rate' => $this->input_data['fenqi_interest_rate'],
    //         'fenqi_images' => $this->input_data['fenqi_images'],
    //         'fenqi_amount' => formatMoneySave($this->input_data['fenqi_amount']),
    //         'fenqi_times' => $this->input_data['fenqi_times'],

    //         'remark' => $this->input_data['remark'],
    //         'create_user' => $this->user['realname'],
    //         'create_user_id' => $this->user['id'],
    //         'create_time' => time(),
    //     ];
    //     $tradeId = db('Trade')->insertGetId($data);

    //     # 更新保险模块
    //     $this->_updateInsurance($tradeId);

    //     # 更新待付款(强险、商业险和中润的对账单)

    //     # 更新应收（欠款）
    //     $this->_updateBill($tradeId);


    //     $this->resSuc('ok');
    // }

    private function _updateBill($tradeId)
    {
        if(formatMoneySave($this->input_data['dianfu_amount']) > 0) $this->_updateDianfu($tradeId);
        if(formatMoneySave($this->input_data['fenqi_amount']) > 0) $this->_updateFenqi($tradeId);

    }

    /**
     * 
     * 保险分期计算公式
     * 
     * 利息 = 本金 * 利息
     * 每期还款本金 = 分期金额 / 分期期数
     * 每期还款利息 = 利息 / 分期期数
     * 总还款金额 = 本金 + 利息
     * 
     * 
     * 每期还款 = 每期还款本金 + 每期还款利息
     * 首期还款金额 = 每期还款 + ( (本金+利息) - (每期还款*分期数) )
     * 
     * 
     * 
     * 垫付计算公式
     * 
     * 
     * 
     *  */

    // 垫付&分期的计算公式
    private function _getBillDetail($cate)
    {
        
        // 期数
        $times = $cate == '垫付' ? $this->input_data['dianfu_times'] : $this->input_data['fenqi_times'];

        // 本金
        $amount = $cate == '垫付' ? $this->input_data['dianfu_amount'] : $this->input_data['fenqi_amount'];
        // 利率
        $interestRate = $cate == '垫付' ? $this->input_data['dianfu_interest_rate'] : $this->input_data['fenqi_interest_rate'];

        /** 
        // 总利息
        $interest = bcmul($amount,$interestRate,2);

        // 每期利息
        $eachInterest = bcdiv($interest,$times,2);

        // 每期本金
        $eachAmount = bcdiv($amount,$times,2);

        // 总账单金额 (每期本金+每期利息) * 还款期数
        $totalAmount = bcmul( bcadd($eachAmount,$eachInterest),$times,2 );

        // 每期还款
        $eachRepay = bcadd($eachAmount,$eachInterest);

        // 首期还款 = 每期还款 + ( (本金+利息) - (每期还款*分期数) )
        $firstRepay = bcadd( $eachRepay, bcsub( bcadd($amount,$interest), bcmul($eachRepay,$times) ) );
        */

        // 首期还款日
        $startDate = $cate == '垫付' ? $this->input_data['dianfu_deadline'] : $this->input_data['fenqi_start_date'];
        
        // 每期的还款日
        $dates = $this->_createRepayDate($startDate,$times);

        // 最后一期还款日
        $lastDateIndex = count($dates) - 1;
        $deadline = $dates[$lastDateIndex];
        
        
        // 账单明细
        $billDetail = [];
        foreach ($dates as $k => $v) {
            $row = [
                'amount' => 10,
                'interest' => 1,
                'deadline' => $v,
                'times' => $k + 1,
            ];
            $billDetail[] = $row;
        }

        return $billDetail;

    }

    // 创建还款日期
    // $day 还款日
    // $times 期数
    private function _createRepayDate($startDate,$times)
    {
        $dates = [];
        $dates[] = $startDate;
        $lastTime = strtotime($startDate);
        for ($i = 1; $i < $times; $i++) {
            $dates[] = $lastDate = date('Y-m-d',strtotime('+1 month',$lastTime));
            $lastTime = strtotime($lastDate);
        }
        return $dates;
    }
    
    // 获取分期方案（前端用）
    public function getInstallmentRepayList()
    {
        $trade = [
            'fenqi_start_date' => $this->input_data['start_date'],
            'fenqi_times' => $this->input_data['times'],
            'fenqi_amount' => $this->input_data['amount'],
            'fenqi_first_pay' => $this->input_data['first_pay'],
            'fenqi_interest_rate' => $this->input_data['interest_rate'],
        ];
        $this->resSuc($this->_createInstallmentBill($trade));
    }

    private function _createInstallmentBill($trade)
    {
        $list = [];

        $dates = $this->_createRepayDate($trade['fenqi_start_date'],$trade['fenqi_times']);
        $lastDateIndex = count($dates) - 1;
        $deadline = $dates[$lastDateIndex];

        // 分期总金额 = 分期金额-首付
        $amount = formatMoneySave($trade['fenqi_amount']) - formatMoneySave($trade['fenqi_first_pay']); 

        $interestRate = bcdiv($trade['fenqi_interest_rate'],100,2);

        $interestOfMonth = bcmul($amount,$interestRate,2); // 每月利息
        $interest = bcmul($trade['fenqi_times'],$interestOfMonth,2); // 总利息

        $amountOfMonth = bcdiv($amount,$trade['fenqi_times'],2); // 每月本金
        $amountTotal = bcmul($amountOfMonth,$trade['fenqi_times']); // 计算出来总共要还的本金

        $amountOfMonthTotal = bcadd($amountOfMonth, $interestOfMonth,2); // 每月需要还款金额

        // 本金差价
        $amountDiff = $amount - $amountTotal;

        $total = 0;
        # 生成账单明细
        foreach ($dates as $k => $v) {
            $total += $amountOfMonthTotal;
            $data = [
                'amount_total' => formatMoneyShow($amountOfMonthTotal),
                'amount' => formatMoneyShow($amountOfMonth),
                'interest' => formatMoneyShow($interestOfMonth),
                'deadline' => $v,
                'times' => $k+1, // 第几期
            ];
            if($k == 0)
            {
                // 第一个月把差价补上
                $data['amount_total'] = formatMoneyShow(bcadd($amountOfMonthTotal,$amountDiff));
                $data['amount'] = formatMoneyShow(bcadd($amountOfMonthTotal,$amountDiff));
            }
            $list[] = $data;
        }
        $total += $amountDiff;
        return [
            'list' => $list,
            'deadline' => $deadline,
            'amount' => $amount,
            'interest' => $interest,
            'total' => formatMoneyShow($total)
        ];
    }


    private function _createFenqiBill($trade,$vehicle)
    {
        $trade['fenqi_amount'] = formatMoneyShow($trade['fenqi_amount']);
        $trade['fenqi_first_pay'] = formatMoneyShow($trade['fenqi_first_pay']);
        $billDetail = $this->_createInstallmentBill($trade);

        # 生成账单主表
        $data = [
            'cate' => '分期',
            'area' => $vehicle['area'],
            'area_id' => $vehicle['area_id'],
            'relation_id' => $trade['id'],
            'trade_id' => $trade['id'],
            'vehicle_id' => $trade['vehicle_id'],
            'grandfather' => $trade['fenqi_grandfather'],
            'grandfather_tel' => $trade['fenqi_grandfather_tel'],
            'amount' => $billDetail['amount'], // 本金
            'interest' => $billDetail['interest'], // 利息
            'interest_rate' => $trade['fenqi_interest_rate'], // 利率
            'times' => $trade['fenqi_times'],
            'deadline' => $billDetail['deadline'],
            'create_user' => $this->user['realname'],
            'create_user_id' => $this->user['id'],
            'create_time' => time(),
        ];
        $bId = db('Bill')->insertGetId($data);
        # 生成账单明细
        foreach ($billDetail['list'] as $v) {
            $v['bill_id'] = $bId;
            $v['amount'] = formatMoneySave($v['amount']);
            $v['amount_total']  = formatMoneySave($v['amount_total']);
            $v['interest']  = formatMoneySave($v['interest']);
            db('BillDetail')->insert($v);
        }
    }
    // 垫付
    private function _createDianfuBill($trade,$vehicle)
    {   
        $amount = $trade['dianfu_amount'];
        # 生成账单主表
        $data = [
            'cate' => '垫付',
            'area' => $vehicle['area'],
            'area_id' => $vehicle['area_id'],
            'relation_id' => $trade['id'],
            'trade_id' => $trade['id'],
            'vehicle_id' => $trade['vehicle_id'],
            'grandfather' => $trade['dianfu_grandfather'],
            'grandfather_tel' => $trade['dianfu_grandfather_tel'],
            'amount' => $amount,
            'times' => 1,
            'interest' => 0,
            'interest_rate' => $trade['dianfu_interest_rate'],
            'deadline' => $trade['dianfu_deadline'],
            'create_user' => $this->user['realname'],
            'create_user_id' => $this->user['id'],
            'create_time' => time(),
        ];
        $bId = db('Bill')->insertGetId($data);
        # 生成账单明细

        $data = [
            'bill_id' => $bId,
            'amount' => $amount,
            'interest' => 0,
            'deadline' => $trade['dianfu_deadline'],
            'times' => 0, 
        ];
        db('BillDetail')->insert($data);

    }

    // private function _updateInsurance($tradeId)
    // {
    //     # 商业险
    //     $list = json_decode($this->input_data['insuranceList'],true);
    //     foreach ($list as $v) {
    //         $u = [
    //             'id' => $v['id'],
    //             'choose' => 1,
    //             'trade_id' => $tradeId
    //         ];

    //         db('Insurance')->update($u);
    //     }

    //     # 其他险种
    //     $other = json_decode($this->input_data['other'],true);
    //     foreach ($other as $v) {
    //         $data = [
    //             'choose' => 1,
    //             'vehicle_id' => $this->input_data['vehicle_id'],
    //             'trade_id' => $tradeId,
    //             'cate' => $v
    //         ];
    //         db('Insurance')->insert($data);
    //     }

    //     # 没有保险，修改状态到出单成功
    //     if(count($list) == 0 && count($other) == 0)
    //     {
    //         db('Trade')->where(['id'=>$tradeId])->update(['status'=>200]);
    //     }
    // }

    // 出单完成
    // public function toDone()
    // {
    //     # 保存并判断是否所有出单要求都已经填写完成
    //     $checkRes = $this->_saveAndCheckOffer($this->input_data['list']);

    //     // $status = $checkRes['tradeRes'] ? 200 : 20;
    //     if( !$checkRes['tradeRes'] ) $this->resErr('没填完所有资料');
    //     $map = [
    //         'id' => $this->input_data['id']
    //     ];
    //     $data = [
    //         'status' => 200,
    //         'done_user' => $this->user['realname'],
    //         'done_user_id' => $this->user['id'],
    //         'judge_time' => time(),
    //     ];
    //     db('Trade')->where($map)->update($data);

    //     $trade = db('Trade')->where($map)->find();

    //     # 出单信息的保险列表
    //     $map = [
    //         'trade_id' => $trade['id'],
    //         'choose' => 1
    //     ];
    //     $insuranceList = db('Insurance')->where($map)->select();

    //     # 更新出单通知的总价
    //     $this->_updateTradePrice($trade,$insuranceList);

    //     # 修改相关报价状态为过期
    //     $this->_updateOfferList($trade);

    //     # 更新车辆保险到期信息
    //     $this->_updateVehicle($trade,$insuranceList);

    //     # 生成应付（中润统筹）

    //     # 生成应收（分期、垫付）



    //     $this->resSuc('出单完成');
    // }

    # 更新车辆报价单状态
    private function _updateOfferList($trade)
    {
        $map = [
            'vehicle_id' => $trade['vehicle_id']
        ];
        $data = [
            'status' => 1
        ];
        db('Insurance')->where($map)->update($data);
    }

    # 更新车辆保险到期信息、更新出单通知的总共应付
    private function _updateVehicle($trade,$insuranceList)
    {
        $map = [
            'id' => $trade['vehicle_id']
        ];

        foreach ($insuranceList as $v) {
            if($v['cate'] == '交强险')
            {
                db('Vehicle')->where($map)->update(['insurance_date_c' => date('Y-m-d',$v['e_time'])]);
            }
            if($v['cate'] == '商业险')
            {
                db('Vehicle')->where($map)->update(['insurance_date_b' => date('Y-m-d',$v['e_time'])]);
            }
        }
    }

    # 更新出单表的应收价格，手动改或者选保险之后
    public function updateTradePrice()
    {
        $data = [
            'glf_price' => formatMoneySave($this->input_data['glf_price']),
            'glf_note' => $this->input_data['glf_note'],
            'gps_price' => formatMoneySave($this->input_data['gps_price']),
            'gps_note' => $this->input_data['gps_note'],
            'eb_price' => formatMoneySave($this->input_data['eb_price']),
            'eb_note' => $this->input_data['eb_note'],
            'xx_price' => formatMoneySave($this->input_data['xx_price']),
            'gz_price' => formatMoneySave($this->input_data['gz_price']),
            'fw_price' => formatMoneySave($this->input_data['fw_price']),
            'qt_price' => formatMoneySave($this->input_data['qt_price']),
        ];

        $qt = json_decode($this->input_data['qtList'],true);
        $qtTitle = [];
        $qtPrice = [];
        foreach ($qt as $v) {
            if($v['price'] > 0)
            {
                $qtTitle[] = $v['title'];
                $qtPrice[] = formatMoneySave($v['price']);
            }
        }
        $data['qt_title'] = implode(',',$qtTitle);
        $data['qt_price'] = implode(',',$qtPrice);

        $data['diff_price_type'] = '';

        $tradeId = $this->input_data['id'];
        db('Trade')->where(['id'=>$tradeId])->update($data);

        // 更新出单表应付的总价
        $data = [
            'tradeId' => $tradeId
        ];
        action('common/Trade/updatePrice',$data);
        $this->_updateProfit($tradeId);

        $this->resSuc('ok');
    }

    private function _updateProfit($tradeId)
    {
        // 更新出单表的利润
        $data = [
            'tradeId' => $tradeId
        ];
        action('common/Trade/updateProfit',$data);
    }

    # 更新出单通知的总价
    private function _updateTradePrice($trade,$insuranceList)
    {
        $price = 0;
        $price = bcadd($price,$trade['glf_price']);
        $price = bcadd($price,$trade['gps_price']);
        $price = bcadd($price,$trade['eb_price']);
        $price = bcadd($price,$trade['xx_price']);
        $price = bcadd($price,$trade['gz_price']); // 盖章费
        $price = bcadd($price,$trade['fw_price']); // 法务费用
        $price = bcadd($price,$trade['qt_price']); // 其他
        foreach ($insuranceList as $v) {
            $price = bcadd($price, $v['price']);
            if($v['cate'] == '商业险') $trade['syx_price'] = $v['price'];
            if($v['cate'] == '交强险') $trade['qx_price'] = $v['price'];
            if($v['cate'] == '货运险') $trade['hyx_price'] = $v['price'];
            if($v['cate'] == '安责险') $trade['azx_price'] = $v['price'];
            if($v['cate'] == '承运险') $trade['cyx_price'] = $v['price'];
            if($v['cate'] == '驾意险') $trade['jyx_price'] = $v['price'];
        }
        $trade['price'] = $price;
        db('Trade')->update($trade);
    }


    private function _saveAndCheckOffer($list)
    {
        $list = json_decode($list,true);

        $total = count($list); // 总共需要购买的保险数量
        $done = 0; // 信息完整的数量
        $payInfo = true; // 付款信息是否完整
        $needPay = false; // 是否需要马上付款给保险公司
        foreach ($list as $v) {
            # 有勾选现付的
            if($v['cash'] == true) $needPay = true;

            # 付款信息是否完整
            if(!$this->_checkPayInfo($v)) $payInfo = false;

            $deadline = $this->_getDeadline($v);

            # 重新计算返点金额
            $rebateAmount = bcmul($v['price'], $v['rebate'],2);

            $nMap = [
                'id' => $v['id']
            ];
            $nData = [
                'price' => formatMoneySave($v['price']),
                's_time' => $deadline['s_time'],
                'e_time' => $deadline['e_time'],
                'cash' => $v['cash'] ? 1 : 0,
                'rebate' => $v['rebate'],
                'rebate_amount' => $rebateAmount
            ];
            
            db('Insurance')->where($nMap)->update($nData);
            if($v['cate'] == '交强险' || $v['cate'] == '商业险')
            {
                if($v['pdf'] != '') $done++;
            }
            else
            {
                if($v['pdf'] != '' && $v['price'] > 0 && $v['insurance_id'] > 0) $done++;
            }
        }

        $data = [
            'tradeRes' => $done == $total,
            'payInfo' => $payInfo,
            'needPay' => $needPay
        ]; 
        return $data;
    }
    private function _getDeadline($v)
    {
        $sh = $v['s_time_h'] ? $v['s_time_h'] : 0;
        $eh = $v['e_time_h'] ? $v['e_time_h'] : 0;
        $si = $v['s_time_i'] ? $v['s_time_i'] : 0;
        $ei = $v['e_time_i'] ? $v['e_time_i'] : 0;


        $s = $v['s_time_date'].' '.$sh.':'.$ei.':00';
        $e = $v['e_time_date'].' '.$eh.':'.$ei.':00';

        $data = [
            's_time' => strtotime($s),
            'e_time' => strtotime($e),
        ];
        return $data;
    }

    // 付款
    public function toPay()
    {
        $tradeId = $this->post('id');
        # 检查付款信息否完整并保存更改过的信息
        $res = $this->_saveAndCheckOffer($this->input_data['list']);
        if(!$res['payInfo']) $this->resErr('请完善保险公司和价格信息');

        $status = $res['needPay'] ? 20 : 30;
        # 完整提交到付款流程
        # 修改出单表的状态，有需要付款的就是20，无需付款的，就到30表示待上传电子保单pdf
        $data = [
            'id' => $tradeId,
            'status' => $status
        ];
        db('Trade')->update($data);

        // 这一步可能会修改返点，所以需要更新一次出单表的利润
        $data = [
            'tradeId' => $tradeId
        ];
        action('common/Trade/updateProfit',$data);

        # 更新出单表所选的保单的状态为待付款或者待上传pdf
        $this->_updateInsuranceStatus($this->input_data['vehicle_id'],$tradeId);

        $this->resSuc('ok');
    }


    # 更新出单表所选的保单的状态为待付款或者待上传pdf
    private function _updateInsuranceStatus($vehicleId,$tradeId)
    {
        $map = [
            'vehicle_id' => $vehicleId,
            'choose' => 1
        ];
        $rows = db('Insurance')->where($map)->select();

        $trade = db('Trade')->where(['id'=>$tradeId])->find();
        foreach ($rows as $v) {
            // 现结的cash=1 保单状态设为10表示待付款 设为20表示待上传pdf
            $v['status'] = $v['cash'] == 1 ? 10 : 20;
            // 车主付款给车队的图片，在保险部提交给财务部付款的时候同步出单表里面的数据
            $v['vehicle_pay_images'] = $trade['pay_images'];
            db('Insurance')->update($v);
        }
    }

    private function _checkPayInfo($v)
    {
        $res = true;
        # 除了中润统筹，其他保险公司的单，都需要填写所属保险公司和价格
        if($v['insurance'] == '' || $v['insurance_id'] == 0) return false;
        if($v['insurance'] != '中润统筹' && $v['price'] * 1 == 0) return false;
        return $res;
    }

    // 付款完毕
    public function payDone()
    {
        # 检查付款图片是否都已经上传完毕
        $done = true;
        $list = json_decode($this->input_data['list'],true);
        foreach ($list as $v) {
            if($v['pay_images'] == '' && $v['cash'] == 1) $done = false;
        }
        if (!$done) $this->resErr('请上传完付款凭证');

        # 创建保险付款记录
        $this->_createInsurancePayRecord($list);

        # 更改出单通知状态
        $data = [
            'id' => $this->input_data['id'],
            'status' => 30,
            'paid_user' => $this->user['realname'],
            'paid_user_id' => $this->user['id'],
            'paid_time' => time(),
        ];
        db('Trade')->update($data);

        $this->resSuc('ok');
    }

    private function _createInsurancePayRecord($list)
    {
        foreach ($list as $v) {
            $data = [
                'cate' => '保险购买',
                'type' => '支出',
                'relation_id' => $this->input_data['id'],
                'relation_name' => $v['insurance'],
                'amount' => formatMoneySave($v['price'] * -1),
                'images' => $v['images'],
                'create_user' => $this->user['realname'],
                'create_user_id' => $this->user['id'],
                'create_time' => time()
            ];

            $repay_record_id = db('PayRecord')->insertGetId($data);
        }
    }

    // 保存付款信息
    public function updateTradePaid()
    {
        $tradeId = $this->input_data['id'];
        $oldTrade = db('Trade')->where(['id'=>$tradeId])->find();
        $data = [
            // 总共付了多少
            'paid' => formatMoneySave($this->input_data['paid']),
            'pay_images' => $this->input_data['pay_images'],
            'pay_time' => strtotime($this->input_data['pay_time']),
            'diff_price_type' => $this->input_data['diff_price_type'],
            'diff_price' => formatMoneySave($this->input_data['diff_price'])
        ];

        
        db('Trade')->where(['id'=>$tradeId])->update($data);

        // 更新出单表应付的总价
        $data = [
            'tradeId' => $tradeId
        ];
        action('common/Trade/updatePrice',$data);
        $this->_updateProfit($tradeId);

        if($this->post('action') == '复核收款金额') $this->_judgePayRecord($tradeId,$oldTrade);

        $this->resSuc('ok');
    }

    private function _judgePayRecord($tradeId,$oldTrade)
    {
        $trade = db('Trade')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number')->where(['a.id'=>$tradeId])->find();

        $this->_deleteTradeOtherData($tradeId);

        # 处理差额
        $this->_createDiff($trade);

        # 创建账单(分期、垫付)
        $this->_createBill($trade);

        # 创建付款记录
        $payRecordId = $this->_createTradePayRecord($trade,$oldTrade);

        # 创建车辆收支记录
        $this->_createCost($trade,$payRecordId,$oldTrade);

        # 更新车辆利润
        action('common/Vehicle/updateProfit',['vehicleId'=>$trade['vehicle_id']]);
    }

    // 保存垫付信息
    public function updateTradeDianfu()
    {
        $data = [
            'id' => $this->input_data['id'],
            'dianfu_amount' => formatMoneySave($this->input_data['dianfu_amount']),
            'dianfu_deadline' => $this->input_data['dianfu_deadline'],
            'dianfu_interest_rate' => $this->input_data['dianfu_interest_rate'],
            'dianfu_images' => $this->input_data['dianfu_images'],
            'dianfu_grandfather_tel' => $this->input_data['dianfu_grandfather_tel'],
            'dianfu_grandfather' => $this->input_data['dianfu_grandfather'],
        ];
        db('Trade')->update($data);
        // 更新出单表应付总价
        $data = [
            'tradeId' => $this->input_data['id']
        ];
        action('common/Trade/updatePrice',$data);
        $this->resSuc('ok');
    }
    // 保存备注信息
    public function updateTradeRemark()
    {
        $data = [
            'id' => $this->input_data['id'],
            'remark' => $this->input_data['remark'],
            'remark_images' => $this->input_data['remark_images'],
        ];
        db('Trade')->update($data);
        $this->resSuc('ok');
    }
    // 保存分期信息
    public function updateTradeInstallment()
    {
        $data = [
            'id' => $this->input_data['id'],
            'fenqi_amount' => formatMoneySave($this->input_data['amount']),
            'fenqi_times' => $this->input_data['times'],
            'fenqi_start_date' => $this->input_data['start_date'],
            'fenqi_charge' => $this->input_data['charge'],
            'fenqi_charge_amount' => formatMoneySave($this->input_data['charge_amount']),
            'fenqi_first_pay_percent' => $this->input_data['first_pay_percent'],
            'fenqi_first_pay' => formatMoneySave($this->input_data['first_pay']),
            'fenqi_interest_rate' => $this->input_data['interest_rate'],
            'fenqi_images' => $this->input_data['images'],
            'fenqi_grandfather_tel' => $this->input_data['fenqi_grandfather_tel'],
            'fenqi_grandfather' => $this->input_data['fenqi_grandfather'],
        ];
        db('Trade')->update($data);

        // 更新出单表应付总价
        $data = [
            'tradeId' => $this->input_data['id']
        ];
        action('common/Trade/updatePrice',$data);

        $this->resSuc('ok');
    }

    // 无法出单
    public function toChoose()
    {
        $tradeId = $this->input_data['id'];
        # 修改出单表状态
        $trade = [
            'status' => 0,
            'id' => $tradeId
        ];
        db('Trade')->update($trade);
        $this->resSuc('操作成功');
    }

    // 出单表提交到审核 - 内勤填完信息 - 提交给财务审核
    public function toJudge()
    {
        $tradeId = $this->input_data['id'];
        # 修改出单表状态
        $trade = [
            'to_judge_time' => time(),
            'to_judge_user' => $this->user['realname'],
            'to_judge_user_id' => $this->user['id'],
            'status' => 5,
            'id' => $tradeId
        ];
        db('Trade')->update($trade);

        $this->resSuc('ok');
    }

    // 出单表提交 - 财务审核通过 - 发给保险部
    public function toBuy()
    {
        $tradeId = $this->input_data['id'];

        # 判断下一步状态到哪里，如果有保险要买，就提交到保险部10，如果没有，就直接变成已完成200
        $iMap = [
            'trade_id' => $tradeId,
            'choose' => 1
        ];
        $status = db('Insurance')->where($iMap)->select() ? 10 : 200;
        # 修改出单表状态
        $trade = [
            'judge_time' => time(),
            'judge_user' => $this->user['realname'],
            'judge_user_id' => $this->user['id'],
            'status' => $status,
            'id' => $tradeId
        ];
        db('Trade')->update($trade);

        $trade = db('Trade')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number')->where(['a.id'=>$tradeId])->find();

        # 处理差额
        $this->_createDiff($trade);

        # 创建账单(分期、垫付)
        $this->_createBill($trade);

        # 创建付款记录
        $payRecordId = $this->_createTradePayRecord($trade);

        # 创建车辆收支记录
        $this->_createCost($trade,$payRecordId);

        # 更新保险单关联的出单表里面的付款时间（报表用）
        $this->_updateInsuranceTradePayTime($trade);

        # 更新车辆利润
        action('common/Vehicle/updateProfit',['vehicleId'=>$trade['vehicle_id']]);


        $this->resSuc('ok');
    }

    # 更新保险单关联的出单表里面的付款时间（报表用）
    private function _updateInsuranceTradePayTime($trade)
    {
        $map = [
            'trade_id' => $trade['id']
        ];
        db('Insurance')->where($map)->update(['trade_pay_time'=>$trade['pay_time']]);
    }

    // 出单的时候创建车辆收支记录
    private function _createCost($trade,$payRecordId,$oldTrade = '无')
    {
        $data['io_type'] = '收入';
        $data['relation_type'] = '出单';
        $data['relation_id'] = $trade['id'];
        $data['trade_id'] = $trade['id'];
        $data['images'] = $trade['pay_images'];
        $data['status'] = 20; // 已完成
        

        if($oldTrade == '无') // 正常出单创建的车辆收支
        {
            $data['pay_user'] = $this->user['realname'];
            $data['pay_user_id'] = $this->user['id'];
            $data['pay_time'] = $trade['pay_time'];
            $data['belongs_date'] = $trade['pay_time']; // 所属日期 = 支付日期
            $data['create_user'] = $this->user['realname'];
            $data['create_user_id'] = $this->user['id'];
            $data['create_time'] = time();
        }
        else
        {
            $data['pay_user'] = $oldTrade['create_user'];
            $data['pay_user_id'] = $oldTrade['create_user_id'];
            $data['pay_time'] = $oldTrade['pay_time'];
            $data['belongs_date'] = $trade['pay_time']; // 所属日期 = 支付日期
            $data['create_user'] = $oldTrade['create_user'];
            $data['create_user_id'] = $oldTrade['create_user_id'];
            $data['create_time'] = $oldTrade['create_time'];
        }
        

        $data['pay_record_id'] = $payRecordId;
        $data['vehicle_id'] = $trade['vehicle_id'];


        # 处理保险收入
        $this->_createInsuranceIncome($trade,$data);

        # 创建差价的收支
        $this->_createDiffPriceCost($trade,$data);

        # 其他费用收入
        # GPS费用
        if($trade['gps_price'] > 0)
        {
            $data['amount'] = $trade['gps_price'];
            $data['cate'] = 'GPS费';
            $data['cate_id'] = 2;
            db('VehicleIncomeExpense')->insertGetId($data);
        }
        # 二保费
        if($trade['eb_price'] > 0)
        {
            $data['amount'] = $trade['eb_price'];
            $data['cate'] = '二保费';
            $data['cate_id'] = 1;
            db('VehicleIncomeExpense')->insertGetId($data);
        }
        # 管理费
        if($trade['glf_price'] > 0)
        {
            $data['amount'] = $trade['glf_price'];
            $data['cate'] = '管理费';
            $data['cate_id'] = 6;
            db('VehicleIncomeExpense')->insertGetId($data);
        }
        # 学习费
        if($trade['xx_price'] > 0)
        {
            $data['amount'] = $trade['xx_price'];
            $data['cate'] = '学习费';
            $data['cate_id'] = 5;
            db('VehicleIncomeExpense')->insertGetId($data);
        }
        # 盖章费
        if($trade['gz_price'] > 0)
        {
            $data['amount'] = $trade['gz_price'];
            $data['cate'] = '盖章费';
            $data['cate_id'] = 9;
            db('VehicleIncomeExpense')->insertGetId($data);
        }
        # 法务费
        if($trade['fw_price'] > 0)
        {
            $data['amount'] = $trade['fw_price'];
            $data['cate'] = '法务费';
            $data['cate_id'] = 8;
            db('VehicleIncomeExpense')->insertGetId($data);
        }
        # 其他费
        if($trade['qt_title'] != '')
        {
            $qt = explode(',', $trade['qt_title']);
            $qtPrice = explode(',',$trade['qt_price']);
            foreach ($qtPrice as $k => $v) {
                if($v > 0)
                {
                    $data['amount'] = $v;
                    $data['cate'] = $qt[$k];
                    $data['cate_id'] = 11;
                    db('VehicleIncomeExpense')->insertGetId($data);
                }
            }
            
        }

    }

    // 出单的时候就算好每一个保险的返点收入
    private function _createInsuranceIncome($trade,$data)
    {
        $map = [
            'trade_id' => $trade['id']
        ];
        $rows = db('Insurance')->where($map)->select();

        foreach ($rows as $v) {
            // 保险收入
            $data['io_type'] = '收入';
            $data['amount'] = $v['price'] + $v['tax_price'];
            $data['cate'] = '保险';
            $data['cate_id'] = 7;
            $data['remark'] = '出单买保险的费用';
            db('VehicleIncomeExpense')->insertGetId($data);

            // 保险支出
            $data['io_type'] = '支出';
            $data['amount'] = $v['price'] + $v['tax_price'];
            $data['cate'] = '保险';
            $data['cate_id'] = 7;
            $data['remark'] = '购买'.$v['insurance'].$v['cate'].'支出';
            db('VehicleIncomeExpense')->insertGetId($data);

            if($v['raise_price'] > 0) // 加价收入
            {
                $data['io_type'] = '收入';
                $data['is_rebate'] = 1;
                $data['amount'] = $v['raise_price'];
                $data['cate'] = '保险';
                $data['cate_id'] = 7;
                $data['remark'] = $v['insurance'].$v['cate'].'加价收入';
                db('VehicleIncomeExpense')->insertGetId($data);
            }
            if($v['rebate_amount'] > 0) // 返点收入
            {
                $data['io_type'] = '收入';
                $data['amount'] = $v['rebate_amount'];
                $data['cate'] = '保险';
                $data['cate_id'] = 7;
                $data['remark'] = $v['insurance'].$v['cate'].'返点收入';
                db('VehicleIncomeExpense')->insertGetId($data);
            }
        }
    }
    // 差价
    private function _createDiffPriceCost($trade,$data)
    {
        if($trade['diff_price_type'] == '优惠')
        {
            $data['io_type'] = '支出';
            $data['amount'] = $trade['diff_price'] * -1;
            $data['cate'] = '多收少收';
            $data['cate_id'] = 10;
            db('VehicleIncomeExpense')->insertGetId($data);
        }
        if($trade['diff_price_type'] == '利润')
        {
            $data['amount'] = $trade['diff_price'];
            $data['cate'] = '多收少收';
            $data['cate_id'] = 10;
            db('VehicleIncomeExpense')->insertGetId($data);
        }
    }

    // 提交到出单的时候，差价如果是欠款，就创建账单，如果是返还，那就创建返还列表
    private function _createDiff($trade)
    {
        if($trade['diff_price'] < 0)
        {
            if($trade['diff_price_type'] == '欠款')
            {
                $this->_createNormalBill($trade);
            }
        }
        if($trade['diff_price'] > 0)
        {
            if($trade['diff_price_type'] == '返还')
            {
                $this->_createReturnMoney($trade);
            }
        }
    }

    // 欠款的账单
    private function _createNormalBill($trade)
    {
        $amount = $trade['diff_price'] * -1;
        $deadline = date('Y-m-d',time() + 2592000);
        # 生成账单主表
        $data = [
            'cate' => '欠款',
            'relation_id' => $trade['id'],
            'trade_id' => $trade['id'],
            'vehicle_id' => $trade['vehicle_id'],
            'amount' => $amount,
            'interest' => 0,
            'interest_rate' => 0,
            'times' => 1,
            'deadline' => $deadline,
            'create_user' => $this->user['realname'],
            'create_user_id' => $this->user['id'],
            'create_time' => time(),
        ];
        $bId = db('Bill')->insertGetId($data);
        # 生成账单明细
        $data = [
            'bill_id' => $bId,
            'amount_total' => $amount,
            // 'amount' => $amountOfMonth,
            // 'interest' => $interestOfMonth,
            'deadline' => $deadline,
            'times' => 1, // 第几期
        ];
        db('BillDetail')->insert($data);
    }

    // 待返还列表
    private function _createReturnMoney($trade)
    {
        $data = [
            'relation_id' => $trade['id'],
            'vehicle_id' => $trade['vehicle_id'],
            'amount' => $trade['diff_price'],
            'create_user' => $this->user['realname'],
            'create_user_id' => $this->user['id'],
            'create_time' => time()
        ];
        db('ReturnMoney')->insert($data);
    }

    private function _createTradePayRecord($trade,$oldTrade = '无')
    {
        // 实付大于0才创建付款记录
        if($trade['paid'] == 0) return true;
        # 保存收款记录
        $data = [
            'pay_time' => $trade['pay_time'],
            'cate' => '出单收款',
            'type' => '收入',
            'relation_id' => $trade['id'],
            'relation_name' => $trade['plate_number'],
            'amount' => $trade['paid'],
            'images' => $trade['pay_images'],
            'create_time' => $trade['pay_time'] // PayRecord表里面的create_time表示付款时间，以trade里面的pay_time为准
        ];

        if($oldTrade == '无')
        {
            $data['status'] = 0;
            $data['create_user'] = $this->user['realname'];
            $data['create_user_id'] = $this->user['id'];
            $data['create_time'] = time();
            
        }
        else
        {
            $data['status'] = 200;
            $data['create_user'] = $oldTrade['create_user'];
            $data['create_user_id'] = $oldTrade['create_user_id'];
            $data['create_time'] = $oldTrade['create_time'];

            $data['judge_user'] = $this->user['realname'];
            $data['judge_user_id'] = $this->user['id'];
            $data['judge_time'] = time();
        }

        $pay_record_id = db('PayRecord')->insertGetId($data);
        return $pay_record_id;
    }

    private function _createBill($trade)
    {
        $vehicle = db('Vehicle')->where(['id'=>$trade['vehicle_id']])->find();
        if($trade['fenqi_amount'] > 0) $this->_createFenqiBill($trade,$vehicle);
        if($trade['dianfu_amount'] > 0) $this->_createDianfuBill($trade,$vehicle);
    }

    // 待付款列表里面的退回操作
    public function cantBuy()
    {
        // 调整报价单状态
        $map = [
            'id' => $this->input_data['id']
        ];
        $data = [
            'status' => 10,
            'cantbuy_content' => $this->input_data['cantbuy_content'],
            'cantbuy_time' => time(),
            'cantbuy_user' => $this->user['realname'],
            'cantbuy_user_id' => $this->user['id'],
            'choose_status' => 4
        ];
        db('Trade')->where($map)->update($data);

        // 删除报价单对应的其他险种(超赔，其他险那些)
        $map = [
            'plan_id' => $this->input_data['id'],
            'cate' => ['NOT IN',['交强险','商业险']]
        ];
        db('Insurance')->where($map)->delete();
        $this->resSuc('ok');
    }

    // 待审出单表 - 退回
    public function setStatus()
    {
        $data = [
            'id' => $this->post('id'),
            'back_reason' => $this->post('back_reason'),
            'status' => $this->post('status'),
            'vehicle_id' => $this->post('vehicle_id'),
            'back_user' => $this->user['realname'],
            'back_user_id' => $this->user['id'],
            'back_time' => time()
        ];
        db('Trade')->update($data);

        if($this->post('status') == 4 || $this->post('status') == 5) $this->_deleteTradeOtherData($this->post('id'));

        $this->resSuc('操作成功');
    }

    // 删除出单表相关的其他数据、欠款、账单、收支等
    private function _deleteTradeOtherData($tradeId)
    {
        # 账单
        $map = [
            'trade_id' => $tradeId
        ];
        $bill = db('Bill')->where($map)->find();
        db('Bill')->where($map)->delete();

        if(isset($bill['id'])) db('BillDetail')->where(['bill_id'=>$bill['id']])->delete();

        # 车辆开支（理论应收付款）
        db('VehicleIncomeExpense')->where($map)->delete();

        # 收支记录
        $map = [
            'relation_id' => $tradeId,
            'cate' => '出单收款',
            'type' => '收入'
        ];
        db('PayRecord')->where($map)->delete();

        $trade = db('Trade')->where(['id'=>$tradeId])->find();
        # 更新车辆利润
        action('common/Vehicle/updateProfit',['vehicleId'=>$trade['vehicle_id']]);

        
    }
    // 删除
    public function del()
    {
        $map = [
            'id' => $this->post('id')
        ];
        
        $data = db('Trade')->where($map)->find();
        if($data['status'] > 5) $this->resErr('此出单表无法删除');

        $this->_deleteTradeOtherData($this->post('id'));
        db('Trade')->where($map)->delete();
        


        $this->resSuc('操作成功');
    }

    public function getById()
    {
        $map = [
            'a.id' => $this->post('id')
        ];
        $data = db('Trade')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number')->where($map)->find();
        $data = $this->_formatTradeData($data);
        $data = $this->_formatQt($data);

        $this->resSuc($data);
    }

}
